package main

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"savor_gin/conf"
	"savor_gin/models"
	"savor_gin/router"
	"savor_gin/utils/valiutils"
)

func main() {

	g := gin.Default()
	//corsConfig := cors.DefaultConfig()
	//corsConfig.AllowAllOrigins = true
	//g.Use(cors.New(corsConfig))
	g.Use(cors())
	router.Load(g)

	//读取配置
	conf := config.Config{}
	if err := conf.InitConfig(); err != nil {
		panic(err) // 读取配置文件失败，直接抛出异常，终止程序运行
	}

	// 初始化验证器
	valiutils.InitValidateUtils()
	// 连接数据库
	models.Init()
	defer models.Close()
	g.Run(viper.GetString("addr"))
}

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 或者指定允许的域名
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Headers", "Content-Type, token") // 根据实际需求修改
		c.Header("Access-Control-Max-Age", "86400")                     // 24 hours
		if method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}
